﻿using Chloe;
using Core.DbContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Core.BLL
{
    public class BaseBLL
    {
        IDbContext _mainDbContext;
        /// <summary>
        /// 主数据库上下文
        /// </summary>
        public IDbContext MainDbContext
        {
            get
            {
                if (this._mainDbContext == null)
                {
                    this._mainDbContext = SqlserverDbContext.CreateContext();

                }
                return this._mainDbContext;
            }
            set
            {
                this._mainDbContext = value;
            }
        }

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Add<T>(T entity) where T : class
        {
            var e = MainDbContext.Insert(entity);
            return e != null;
        }

       /// <summary>
        /// 批量添加
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public void Add<T>(List<T> list) where T : class
        {
             MainDbContext.InsertRange(list);            
        }

        /// <summary>
        /// 修改实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Update<T>(T entity) where T : class
        {
            int r = MainDbContext.Update(entity);
            return r>0;
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete<T>(T entity) where T : class
        {
            int r = MainDbContext.Delete(entity);
            return r > 0;
        }

        /// <summary>
        /// 指定条件删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where"></param>
        /// <returns></returns>
        public bool Delete<T>(Expression<Func<T, bool>> where) where T : class
        {
            int r = MainDbContext.Delete<T>(where);
            return r > 0;
        }

       /// <summary>
       /// 查询详情
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <param name="where"></param>
       /// <returns></returns>
       public T Detail<T>(Expression<Func<T, bool>> where) where T : class
        {
            return MainDbContext.Query<T>().Where(where).FirstOrDefault();
        }

        public T QueryById<T>(object key) where T: class
        {
            return MainDbContext.QueryByKey<T>(key);
        }
    }
}
